/*
 *  File : ShortenUrl.java
 *  Created By : madhurt
 *  Created On : Oct 12, 2010
 *  Yahoo! 2010
 */
package com.gebogebo;

import com.gebogebo.ds.PMF;
import com.gebogebo.ds.URLEntryDAO;
import com.google.appengine.api.datastore.Link;
import java.io.IOException;
import java.io.PrintWriter;
import javax.jdo.JDOCanRetryException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author madhurt
 */
public class ShortenUrl extends HttpServlet {

    private final URLEntryDAO dao = new URLEntryDAO();
    private final VariableLengthStringKeyGenerator keyGen = new VariableLengthStringKeyGenerator(3);
    private static final int KEY_GEN_MAX_RETRY_COUNT = 3;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String longURL = request.getParameter("incoming_url");
        
        URLEntry urlEntry;
        
        String shortKey = checkIfAlreadyShortened(longURL);
        if(shortKey == null) {
            urlEntry = generateUniqueKey(longURL);
            shortKey = urlEntry.getShortKey();
        }
        
        String shortURL = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + shortKey;
        
        request.setAttribute("shortKey", shortKey);
        request.setAttribute("longURL", longURL);
        request.setAttribute("shortURL", shortURL);
        
        RequestDispatcher dispatcer = request.getRequestDispatcher("shorten.jsp");
        dispatcer.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private URLEntry generateUniqueKey(String longURL) {
        PersistenceManager pmf = PMF.get().getPersistenceManager();
        URLEntry entry = null;
        JDOCanRetryException exception = null;

        for (int i = 0; i < KEY_GEN_MAX_RETRY_COUNT; i++) {
            Transaction tx = pmf.currentTransaction();
            tx.begin();

            String shortCode = keyGen.generateKey();
            Link link = new Link(longURL);

            entry = new URLEntry(shortCode, link);

            try {
                pmf.makePersistent(entry);
                tx.commit();
                break;

            } catch (JDOCanRetryException ex) {
                entry = null;
                exception = ex;
            }
        }

        if (entry == null) {
            throw exception;
        }

        return entry;
    }

    private String checkIfAlreadyShortened(String longURL) {
        URLEntry entry = dao.getURLEntryForLongURL(longURL);
        if(entry == null) {
            return null;
        }
        
        return entry.getShortKey();
    }
}
